package org.idea.servlet;

import com.google.gson.Gson;
import org.idea.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 实现异步用户登录
 *
 * @Author zqx
 * @Date 2023-10-25
 */
@WebServlet("/login-ajax.do")
public class LoginAjaxServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 第一：获取客户端浏览器输入的数据
        String username = req.getParameter("uname");
        String password = req.getParameter("upass");

        // 第二：验证数据的合法性

        // 第三：加工处理 - 实现业务 - 业务对象 - DAO对象
        // username == null -- 短路运算
        PrintWriter out = resp.getWriter();
        if(!(username!=null && "".equals(username.trim())) && !(password!=null && "".equals(password.trim()))) {
            // 第四：响应回客户端浏览器
            // out.print("{username:'zs',password:'123456',....,..,..,...}");
            User user = new User(username,password) ;
            String json = new Gson().toJson(user);
            out.print(json) ;
        } else {
            out.print("error");
        }

        out.flush();
        out.close();

    }
}
